package com.zhanggm.zyk.order.controller;


import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhanggm.zyk.order.config.AjaxResult;
import com.zhanggm.zyk.order.entity.Order;
import com.zhanggm.zyk.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-03
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Autowired
//    @Resource
    private IOrderService iOrderService;

    String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJKkN8T7otSL6FHXKabFxZLd+NEz/YfIrKtfFvSPS1xy89LUyDEah9ucMNXSSPaTifzzZ55XTEOSpAwf/2ESbxfL+7FB8iMvrVOxmAXmNuLGw9RK4CZgDmY0uueqgFJO32CN673nx5d5Iyd4IFFCmnmORyddQl0UpNiSp0TpC7AtIQduxFuD79uWchDEDmA+h2aJdoMNTbi4HNrXkBuVnUSEz2a9541XFnRWGlnoeFtoPuYmLc0TLRHYsNL37vT4Yb5hXjv+KNLDaB2JTWlkqHdiUAJaQMi97rzLAEh4HyY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ZuhwITPcL0UECgYEAyp3S1/o0tOKWG1dQ9occFk4eMrP6f6zgFNhL/aW469Dcy+WuAIG70y2T2CMxDNDmKbnDN/pAQZKHmxGO4oygj9s1ypX8rp+uf8YbfdFd22qbsNrxBZHwp9Cxhp/yID7mCZmpaAqCmcr9uszF2BpuFix0XtOSyrbU4oZzZ8EayK4=";
    String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqr4kPoICbZBYfBbxgX/3i9+yVLjMJIslrFJTYOKYWk9Dq4LPGEUl415jZZB6cQZjStqDVA/tiQOyAgghmgD9CIVYFX31Z28/IaruAvuas8LgKUAhXpA33mmJChvrevfOiXTFVh+bepc1s0ED34+cFMsnkGLyJvvzIQWqoaet4XgR+4+x6mE885wJCpFqjFNXAUPrT5l5hE5m3hMTp+nIya2qogNaITIlR6Liuj6r9voRTLTZUm48umc7YhP6G9AJzu15vvjGkyNCx4u5M49KS61P13FRsIwYmAtMZPZ41u+ZoBcGanIGwRwghWSSPR/0GtAjExy8/zzaAAQATfthDQIDAQAB";


    @GetMapping("page")
    public AjaxResult page() {
        PageHelper.startPage(1, 200);
        List<Order> list = iOrderService.list();
        return AjaxResult.success(new PageInfo<>(list));
    }


    @GetMapping("pay")
    public String pay(Long id) throws AlipayApiException {
        //查询订单信息
        Order order = iOrderService.getById(id);
        //调用支付宝下单
       AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000137666570");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(order.getOrderId()+"");
        model.setTotalAmount(order.getOrderAmount()+"");
        model.setSubject("Iphone6 16G");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        request.setBizModel(model);

        //设置回调接口 setReturnUrl前端回调 不安全
        request.setReturnUrl("http://localhost/order");

        //setNotifyUrl 后端回调 安全
//        request.setNotifyUrl("http://localhost:8100/order/order/callback");

        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
        String tradeNo = response.getTradeNo();


        log.info("tradeNo:{},outTradeNo:{}", response.getTradeNo(), response.getOutTradeNo());





        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return pageRedirectionData;

    }

    @Autowired
    HttpServletRequest request;



    @PostMapping("callback")
    public AjaxResult callback(@RequestBody Map<String,String> paramsMap) throws UnsupportedEncodingException, AlipayApiException {
//获取支付宝GET过来反馈信息
    /*    Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }*/

        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, alipayPublicKey, "utf-8", "RSA2"); //调用SDK验证签名
        if (signVerified) {
            String out_trade_no = paramsMap.get("out_trade_no");
            Order order = iOrderService.getById(out_trade_no);
            order.setStatus("已支付");
            iOrderService.saveOrUpdate(order);
        }

        return AjaxResult.success();
    }


    @GetMapping("query")
    public AjaxResult query(Integer id) throws AlipayApiException {
        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJKkN8T7otSL6FHXKabFxZLd+NEz/YfIrKtfFvSPS1xy89LUyDEah9ucMNXSSPaTifzzZ55XTEOSpAwf/2ESbxfL+7FB8iMvrVOxmAXmNuLGw9RK4CZgDmY0uueqgFJO32CN673nx5d5Iyd4IFFCmnmORyddQl0UpNiSp0TpC7AtIQduxFuD79uWchDEDmA+h2aJdoMNTbi4HNrXkBuVnUSEz2a9541XFnRWGlnoeFtoPuYmLc0TLRHYsNL37vT4Yb5hXjv+KNLDaB2JTWlkqHdiUAJaQMi97rzLAEh4HyYE7H7f4p9q52ELwn1oEX+RemNdWyj2VzOyeZo57eSZD3AgMBAAECggEAWEhIeUlDVgQdA8ZJTdTytz9MRBugmzDFj+T8yRiW0CysXd67AR0raghW31IUxuz9UfZnZJtnxSfZ5yY2HWU6wHD/YmR4CWXwha9tIW8e5flXjTOYH9kROTetrVYqsGztb86TtS1kxjVMdojuuWAZ01IXrwfhjJmhDjh7h7JNet9DQlhhmM/aiCPqlxdOulNwcUVqy7ITL8QTcHUz3AxDE1s/o1Zs8eqvE9w7E6r5pPp71g0U4BtXhtSbnP4XdRVnpo9KVG/tAfMqrdaU+CLmEMB8+i9+qRsz01qJAvfE1LDJB3cFMG85Ew1N0LLA16fuYpCuPdJjSGRjiR1pDEtV8QKBgQDzxe/c1oji8ho97eFjt0k9/EyDfWRtladF1J6pVdumL3/adL9JuSlrIWtCBt4qGFLlMKBzMvTpSEAaHf3pxgqxUEDHa1vum4t/swL25bNrA+fp0afH2Tkc2u9ejD6k9olrLX3yGf5w/cSURltGQo8GdK94yuZwLOfdYRyMSuj83wKBgQCQC3jUIdNi9tUXqo8eyqMHO4g/JYYQPkqcxYJdWLTqr79z9BgcgYbdEQl5khQwcYuyA25fFa0rSpVQP6pazMI4WM0C2eUQWp8y9pEwcC4S6kJjMnIhKngk340QhYQ8//sZU0V01hYaXVrCQQR17QMlu/p73cgiZMOIMGz8lUfW6QKBgAXLkNY5K2vpwYHzY8ZRFyaoFtGRa4/HXQCl+1efOOeMfYed+uYvxrJLSxd4vlNV3LKiI05ZycS5+Pwl9mFWWe65L7EN9lOH0xsoEEv6TfefUiYW29w+Z8Mt2T7wKpUVX1Ly8+mLgKcDAWdc/NKAxpGquHkwqaXFC4YRxvH23e8VAoGARe3L0vA49yptePfMU158lt5H3qAQ3YHgJwubpkWSTvzTLS+rJOuc1WWX+/T26C23a8xOoMqdLw8ePb8qrLoK79/sZx3xHmdgMhWRlrpfI7+mSxIKZh+ABCajDQpEkHiVJk5OwdHNGS+JCBUYXUea547Co6+foVLZuhwITPcL0UECgYEAyp3S1/o0tOKWG1dQ9occFk4eMrP6f6zgFNhL/aW469Dcy+WuAIG70y2T2CMxDNDmKbnDN/pAQZKHmxGO4oygj9s1ypX8rp+uf8YbfdFd22qbsNrxBZHwp9Cxhp/yID7mCZmpaAqCmcr9uszF2BpuFix0XtOSyrbU4oZzZ8EayK4=";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqr4kPoICbZBYfBbxgX/3i9+yVLjMJIslrFJTYOKYWk9Dq4LPGEUl415jZZB6cQZjStqDVA/tiQOyAgghmgD9CIVYFX31Z28/IaruAvuas8LgKUAhXpA33mmJChvrevfOiXTFVh+bepc1s0ED34+cFMsnkGLyJvvzIQWqoaet4XgR+4+x6mE885wJCpFqjFNXAUPrT5l5hE5m3hMTp+nIya2qogNaITIlR6Liuj6r9voRTLTZUm48umc7YhP6G9AJzu15vvjGkyNCx4u5M49KS61P13FRsIwYmAtMZPZ41u+ZoBcGanIGwRwghWSSPR/0GtAjExy8/zzaAAQATfthDQIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000137666570");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo("20240603"+id);
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return AjaxResult.success(response.getBody());
    }


    @PostMapping
    public AjaxResult save(@RequestBody Order order) {

        long id = IdUtil.getSnowflakeNextId();
        order.setOrderId(id+"");

        iOrderService.save(order);
        return AjaxResult.success();
    }

}
